package com.xiaochi.subject.domain.utli;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 缓存工具类
 *
 * 可以用于全部的地方进行缓存
 * 而不用每次都写一遍
 *
 * 这里有并发读写问题
 * 还有redis缓存 数据库都可以在这里
 *
 * @author zqx
 * @since 2024/9/5
 */
@Component
public class CacheUtil<K,V> {

    private Cache<String,String> localCache =
            CacheBuilder.newBuilder()
                    .maximumSize(5000)
                    .expireAfterWrite(10, TimeUnit.SECONDS)
                    .build();

    public List<V> getResult(String cacheKey, Class<V> clazz, Function<String,List<V>> function){
        //这里可以写 本地缓存 -> redis缓存 -> 数据库 的逻辑
        String content = localCache.getIfPresent(cacheKey);
        List<V> resultList = new ArrayList<>();
        if (StringUtils.isNotBlank(content)){
            return resultList = JSON.parseArray(content,clazz);
        }else {
            resultList = function.apply(cacheKey);
            if (!CollectionUtils.isEmpty(resultList)){
                localCache.put(cacheKey,JSON.toJSONString(resultList));
            }
        }
        return resultList;
    }

    public Map<K,V> getMapResult(String cacheKey,Class<V> clazz,Function<String,Map<K,V>> function){
        String content = localCache.getIfPresent(cacheKey);
        Map<K,V> resultMap = new HashMap<>();
        List<Map<K,V>> resultMapList = new LinkedList<>();
        if (StringUtils.isNotBlank(content)){
        }
        return new HashMap<>();
    }
}
